package edu.temple.mobile.parsing.helpers;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import edu.temple.mobile.parsing.RouteCoord;

public class XMLHelper extends DefaultHandler {
	
	private boolean inPlaceMark;
	private boolean inName;
	private boolean inMultiGeometry;
	private boolean inLineString;
	private boolean inCoordinates;
	
	private Integer rowCount = 0;

	
	Boolean currentElement = false;
	String currentValue = null;
	private RouteCoord routeCoord = new RouteCoord();

	public RouteCoord getRouteCoord() {
		return this.routeCoord;
	}
	
	@Override
    public void startDocument() throws SAXException {
            // Do some startup if needed
    }

	/**
	 * Called when tag starts ( ex:- <name>AndroidPeople</name> -- <name> )
	 */
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes atts) throws SAXException {
		//Gets placemark ID
		if (localName.equals("Placemark")){
			this.inPlaceMark = true;
			String attrValue = atts.getValue("id");
			routeCoord.setRouteID(attrValue);
		}else if (localName.equals("name")){
			this.inName = true;
		}else if (localName.equals("MultiGeometry")){
			this.inMultiGeometry = true;
		}else if (localName.equals("LineString")){
			this.inLineString = true;
		}else if (localName.equals("coordinates")){
			this.inCoordinates = true;
			routeCoord.setCoordRows(rowCount + 1);
		}
	}

	/**
	 * Called when tag closing ( ex:- <name>AndroidPeople</name> -- </name> )
	 */
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		
		if (localName.equals("Placemark")){
			this.inPlaceMark = false;
		}else if (localName.equals("name")){
			this.inName = false;
		}else if (localName.equals("MultiGeometry")){
			this.inMultiGeometry = false;
		}else if (localName.equals("LineString")){
			this.inLineString = false;
		}else if (localName.equals("coordinates")){
			/** End line character for string is E*/
			routeCoord.setCoordinates("E");
			this.inCoordinates = false;
		}

	}

	/**
	 * Called to get tag characters ( ex:- <name>AndroidPeople</name> -- to get
	 * AndroidPeople Character )
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if(this.inCoordinates){
			String commas = new String(ch, start, length);
			commas = commas.replaceAll(" ", "s");
			commas = commas.replaceAll(",", "c");
			commas = commas.replaceAll("/n","");
			commas = commas.replaceAll("/t","");
            routeCoord.setCoordinates(commas);
		}
	}
	
	@Override
    public void endDocument() throws SAXException {
            // Do some finishing work if needed
    }

}
